<template>
  <base-breadcrumb :title="titleName">
    <searchData
      ref="searchData"
      :search-data="searchArr"
      @search="search"
    />
    <a-card :bordered="false">
      <a-tabs
        v-model="run"
        @change="tabsChange"
      >
        <a-tab-pane key="0">
          <template slot="tab">
            <a-badge
              :count="tipCountInfo.audit"
              :number-style="{ backgroundColor: '#F59A23' }"
              :offset="[6, 0]"
            >
              <span>未结束</span>
            </a-badge>
          </template>
        </a-tab-pane>
        <a-tab-pane key="1">
          <template slot="tab">
            <span>已结束</span>
          </template>
        </a-tab-pane>
      </a-tabs>
    </a-card>
    <div class="table">

      <!-- <a-table ref="table" :pagination="false" :columns="columns" :data-source="tableData" row-key="taskId"> -->
      <list-table
        ref="table"
        row-key="taskId"
        :columns="columns"
        :request="loadData"
        :alert="true"
      >
        <span
          slot="serial"
          slot-scope="text, record, index"
        >{{ index + 1 }}</span>
        <span
          slot="taskSource"
          slot-scope="text"
        >
          <ellipsis
            :length="8"
            tooltip
          >{{ text | taskSourceFilter }}</ellipsis>
        </span>
        <template
          slot="result"
          slot-scope="text"
        >
          <div>
            <span v-show="text == '0'">审核中</span>
            <span v-show="text == '1'">审核通过</span>
            <span v-show="text == '2'">审核不通过</span>
            <span v-show="text == '3'">撤回</span>
            <span v-show="text == '4'">已删除</span>
          </div>
        </template>
        <template
          slot="action"
          slot-scope="text, record"
        >
          <MoreButton>
            <a
              v-if="record.detailUrl"
              @click="handleToDetail(record)"
            >查看</a>
            <!-- <sapan @click="handleToDetail(record)">查看详情</a> -->
            <a @click="checkAuditDetail(record)">审批信息</a>
            <a
              v-if="record.startRecall && run === '0'"
              v-btnPermission="'ma_003_und_06'"
              @click="handleWithdraw(record)"
            >撤回</a>
            <a
              v-if="run === '0'"
              v-btnPermission="'ma_003_has_05'"
              @click="handleUrge(record)"
            >催办</a>
          </MoreButton>
        </template>
      </list-table>
      <!-- <pagination v-model="pageNo" :total="totalSize" :page-size.sync="pageSize" @change="handlePageChange" @showSizeChange="showSizeChange" /> -->
    </div>
    <!-- 审核详情 -->
    <ApprovalDetails
      :title="'审批意见'"
      :procInstId="childInitData.procInstId"
      :businessId="childInitData.businessId"
      :visible="visibleState.isAudit"
      @cancel="visibleState.isAudit = false"
      @confirm="visibleState.isAudit = false"
    />
  </base-breadcrumb>
</template>

<script>
import ApprovalDetails from './approvalDetails'
import { Ellipsis } from '@/components'
import Vue from 'vue'
import BusinessTodo from '../BusinessTodo.vue'
import { BUSINESS_SOURCE_MAP } from '@/config/businessConfig.js'
import { toAuditDetail } from '@/utils/util'
import { getSelfAudit, ugre, recall } from '@/api/indexPage'

const searchBusinessArr = [
  {
    name: '标题',
    value: 'noticeTitle',
    type: 'input'
  },
  {
    name: '内容',
    value: 'noticeContent',
    type: 'input'
  }
]

const searchArr = [
  // 搜索框
  {
    name: '事项名称',
    value: 'processName',
    type: 'input'
  },
  {
    name: '事项来源',
    value: 'taskSource',
    type: 'select',
    data: Object.keys(BUSINESS_SOURCE_MAP).map((key) => {
      return {
        label: BUSINESS_SOURCE_MAP[key],
        value: key
      }
    })
  },
  {
    name: '状态',
    value: 'status',
    type: 'select',
    data: [
      {
        label: '审核中',
        value: '0'
      }
    ]
  },
  {
    name: '创建时间',
    value: 'startEndDate',
    type: 'dateRange',
    attr: {
      rangeFormat: ['startTime', 'endTime']
    }
  }
]

const columns = [
  {
    title: '序号',
    width: '100px',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '事项名称',
    dataIndex: 'name'
  },
  {
    title: '事项来源',
    dataIndex: 'taskSource',
    scopedSlots: { customRender: 'taskSource' }
  },
  {
    title: '创建时间',
    dataIndex: 'startTime'
  },
  {
    title: '状态',
    dataIndex: 'result',
    scopedSlots: { customRender: 'result' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '180px',
    scopedSlots: { customRender: 'action' }
  }
]

const statusApproval = {
  false: { text: '审核通过', status: 'success' },
  true: { text: '审核不通过', status: 'warning' }
}

const taskSourceMap = BUSINESS_SOURCE_MAP

export default {
  name: 'DoneTableList',
  components: {
    Ellipsis,
    ApprovalDetails,
    BusinessTodo
  },
  data() {
    return {
      tipCountInfo: {
        // 待办数统计提示
        audit: 0,
        business: 0
      },
      childQuery: {}, // 子级参数
      searchBusinessArr,
      // activeKey: 'audit',
      visibleState: {
        isAudit: false
      },
      childInitData: {},
      searchArr,
      columns,
      titleName: '',
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      selectedRowKeys: [],
      selectedRows: [],
      tableData: [],
      totalSize: 1,
      pageNo: 1,
      pageSize: 10,
      run: '0', //运行状态

      loadData: (parameter) => {
        const userInfo = Vue.getAcloudProvider().getUserInfo()
        const requestParameters = Object.assign({}, parameter, this.queryParam, { startUserId: userInfo.id, run: this.run })
        return getSelfAudit(requestParameters).then((res) => {
          res.data.forEach((d) => {
            if (d.formData) {
              d.formData = JSON.parse(d.formData)
            }
          })
          this.totalSize = res.totalSize
          //查询条数
          if (this.run === '0') {
            this.tipCountInfo.audit = res.totalSize || 0
          }

          return res
        })
      }
    }
  },

  created() {
    this.currentUser = Vue.getAcloudProvider().getUserInfo()
    // this.list()
  },
  filters: {
    taskSourceFilter(type) {
      return taskSourceMap[type]
    }
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        selectedRows: this.selectedRows, // 当前行所有数据
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    /**
     * tabs切换
     */
    tabsChange() {
      searchArr.forEach((item) => {
        if (item.value === 'status' && this.run === '0') {
          item.data = [
            {
              label: '审核中',
              value: '0'
            }
          ]
        } else if (item.value === 'status' && this.run === '1') {
          item.data = [
            {
              label: '审核通过',
              value: '1'
            },
            {
              label: '审核不通过',
              value: '2'
            },
            {
              label: '撤回',
              value: '3'
            },
            {
              label: '已删除',
              value: '4'
            }
          ]
        }
      })
      this.$refs.searchData.handleReset()
      // this.list()
      this.$refs.table.refresh(true)
    },
    checkAuditDetail(data) {
      this.childInitData = { ...data }
      this.visibleState.isAudit = true
    },
    handleToDetail(data) {
      toAuditDetail.call(this, data)
    },
    //查询
    list(parameter, callback) {
      const _this = this
      const userInfo = Vue.getAcloudProvider().getUserInfo()
      const requestParameters = Object.assign({ pageSize: callback ? _this.totalSize : _this.pageSize, pageNo: _this.pageNo, startUserId: userInfo.id, run: this.run }, parameter, this.queryParam)
      getSelfAudit(requestParameters).then((res) => {
        res.data.forEach((d) => {
          if (d.formData) {
            d.formData = JSON.parse(d.formData)
          }
        })
        _this.tableData = res.data
        _this.totalSize = res.totalSize
        //查询条数
        if (this.run === '0') {
          this.tipCountInfo.audit = res.totalSize || 0
        }
      })
    },
    // })
    handlePageChange(pageNo) {
      this.pageNo = pageNo
      this.list()
    },
    showSizeChange(pageNo, pageSize) {
      this.pageNo = 1
      this.pageSize = pageSize
      this.list()
    },
    search(val) {
      this.queryParam = val
      // this.list()
      this.$refs.table.refresh(true)
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    /**
     * @description: 撤回
     * @param {object} record 行数据
     * @return {void}
     */
    handleWithdraw({ procInstId }) {
      this.$confirm({
        content: '确认撤回至草稿状态？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          const { id: userId } = Vue.getAcloudProvider().getUserInfo()
          return new Promise(async (resolve) => {
            try {
              const res = await recall({
                formData: {
                  opinions: '撤回至草稿状态'
                },
                procInstId,
                userId,
                // 我发起: 0,管理员撤回: 1
                type: 0
              })
              if (res.code === this.SUCCESS_CODE) {
                this.$message.success('撤回成功')
                this.search()
              }
              resolve()
            } catch (error) {
              console.log(error)
              resolve()
            }
          })
        }
      })
    },
    /**
     * @description: 催办
     * @param {object} record 行数据
     * @return {void}
     */
    handleUrge({ procInstId }) {
      this.$confirm({
        content: '确认催办？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          return new Promise(async (resolve) => {
            try {
              await ugre(procInstId)
              resolve()
            } catch (error) {
              resolve()
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.table {
  height: auto;
  background: #fff;
  padding-bottom: 10px;
  margin-top: -12px;
}
</style>

